# coding=utf8
from django.template.context import RequestContext
from django.shortcuts import render_to_response
from django.http import HttpResponse, Http404
from django.http import HttpResponseRedirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, PasswordChangeForm
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth import authenticate, login as auth_login
from django.views.decorators.csrf import csrf_protect

from tussin.accounts.forms import TussinUserCreationForm

def register(request):
    if request.method == "POST":
        form = TussinUserCreationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/accounts/login/")
    else:
        form = TussinUserCreationForm()
    return render_to_response("accounts/register.html", {'form': form}, context_instance=RequestContext(request))

def login(request):
    if request.method == "POST":
        if request.session.test_cookie_worked():
            request.session.delete_test_cookie()
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    auth_login(request, user)
                    return HttpResponseRedirect("/accounts/")
            else:
                return HttpResponseRedirect("/accounts/login/")
        else:
            return HttpResponse("你的浏览器已经禁用cookie，导致无法登录我们的网站。请设置启用cookie")
    else:
		form = AuthenticationForm(request)
    request.session.set_test_cookie()
    return render_to_response("accounts/login.html", {'form': form}, context_instance=RequestContext(request))

@login_required
def profile(request):
	return render_to_response("accounts/profile.html", {'iuser': request.user}, context_instance=RequestContext(request))

@login_required
def change_pass(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.POST)
        if (request.POST['new_password1'] == request.POST['new_password2'] and request.user.check_password(request.POST['old_password'])):
            request.user.set_password(request.POST['new_password1'])
            msg = '密码修改成功'
            request.user.message_set.create(message=msg)
            return HttpResponseRedirect("/accounts/")
        else:
            msg = '输入的旧密码不正确'
    else:
        form = PasswordChangeForm(request)
        msg = ''

    request.user.message_set.create(message=msg)
    return render_to_response('accounts/password_change_form.html', {'form':form}, context_instance=RequestContext(request))

